package scanner

import (
	"learning/gooop/spring/autogen/domain"
	"regexp"
)

type IImportScanner interface {
	ScanImport(file *domain.CodeFileInfo)
}

type tImportScanner int

func (me *tImportScanner) ScanImport(file *domain.CodeFileInfo) {
	me.parseSingleImport(file)
	me.parseMultiImports(file)
}

func (me *tImportScanner) parseSingleImport(file *domain.CodeFileInfo) {
	for _, it := range file.CleanLines {
		if gSingleImportRegexp.MatchString(it) {
			ss := gSingleImportRegexp.FindAllStringSubmatch(it, -1)[0]
			imp := domain.NewImportInfo()
			imp.CodeFile = file

			if len(ss) == 3 {
				imp.Alias = ""
				imp.Package = ss[1]
			} else if len(ss) == 5 {
				imp.Alias = ss[1]
				imp.Package = ss[3]
			}

			file.AppendImport(imp)
		}
	}
}

func (me *tImportScanner) parseMultiImports(file *domain.CodeFileInfo) {
	bInBlock := false
	for _, it := range file.CleanLines {
		if bInBlock {
			if gMultiImportEnd.MatchString(it) {
				bInBlock = false
				continue
			}

			if gImportPackage.MatchString(it) {
				ss := gImportPackage.FindAllStringSubmatch(it, -1)[0]
				imp := domain.NewImportInfo()
				imp.CodeFile = file

				if len(ss) == 3 {
					imp.Alias = ""
					imp.Package = ss[1]
				} else if len(ss) == 5 {
					imp.Alias = ss[2]
					imp.Package = ss[3]
				}
			}
		}

		if gMultiImportStart.MatchString(it) {
			bInBlock = true
			continue
		}
	}
}

var gSingleImportRegexp = regexp.MustCompile(`\s*import\s+((\w+|\.)\s+)?("\w+(/\w+)*")`)
var gMultiImportStart = regexp.MustCompile(`^\s*import\s+\(`)
var gMultiImportEnd = regexp.MustCompile(`^\s*\)`)
var gImportPackage = regexp.MustCompile(`^\s*((\w+|\.)\s+)?("\w+(/\w+)*")`)

var DefaultImportScanner IImportScanner = new(tImportScanner)
